#!/usr/bin/env python
################################################################################
# EasyGMap Map Builder                                                         #
#                                                                              #
# Copyright (c) 2007 Tim Kersten                                               #
# MyMeteor Python Bindings are available at                                    #
# http://code.google.com/p/mymeteorpytonbindings/                              #
#                                                                              #
# Permission is hereby granted, free of charge, to any person obtaining a copy #
# of this software and associated documentation files (the "Software"), to     #
# deal in the Software without restriction, including without limitation the   #
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or  #
# sell copies of the Software, and to permit persons to whom the Software is   #
# furnished to do so, subject to the following conditions:                     #
#                                                                              #
# The above copyright notice and this permission notice shall be included in   #
# all copies or substantial portions of the Software.                          #
#                                                                              #
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR   #
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,     #
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE  #
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER       #
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,              #
# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER  #
# DEALINGS IN THE SOFTWARE.                                                    #
################################################################################


import urllib2, urllib

VERSION = "0.2.0alpha1"

class MyMeteor:
	"""
	Bindings to mymeteor.ie
	"""
	
	def __init__(self):
		self.version = VERSION
		self.cookie = "";
		self.referer = "https://www.mymeteor.ie/";
	
	def connect(self):
		url = 'https://www.mymeteor.ie/mymeteor/login.cfm'
		headers ={'User-agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Ubuntu 6.10)',
				  'Referer' : self.referer}
		handle = self.request(url, headers)
		returnedHeaders = str(handle.info()).split("\n")
		for line in returnedHeaders:
			if line[12:16] == "CFID":
				self.cookie += line[12:24] + "; "
			elif line[12:16] == "CFTO":
				self.cookie += line[12:28] + ";"
		self.referer = handle.geturl()
	
	def login(self, phoneNumber, pin):
		self.connect()
		params = urllib.urlencode({
			'msisdn': phoneNumber,
			'pin': pin,
			'method': "login",
			'returnTo': "/mymeteor/login.cfm",
			'business_r29_c52': "true"
		})
		url = 'https://www.mymeteor.ie/mymeteor/system/controllers/controller.cfc'
		headers ={'User-agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)',
				  'Cookie' : self.cookie,
				  'Referer' : self.referer}
		handle = self.request(url, headers, params)
		if handle.geturl() == "https://www.mymeteor.ie/mymeteor/system/view/home.cfm":
			self.referer = handle.geturl()
			return True
		return False
	
	def sendMessage(self, to, message):
		params = urllib.urlencode({
			'msisdn': to,
			'sms_text': message,
			'formName' : "smsForm",
			'mum_left' : "0",
			'phonebook' : "Select From Phonebook",
			'sendSMS' : "Please wait...",
			'clicked' : "1",
			'action' : "Send SMS",
			'method': "SMS",
			'returnTo': "/mymeteor/system/view/sms.cfm",
			'business_r29_c52': "true"
		})
		url = 'https://www.mymeteor.ie/mymeteor/system/controllers/controller.cfc'
		headers ={'User-agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)',
				  'Cookie' : self.cookie,
				  'Referer' : "https://www.mymeteor.ie/mymeteor/system/view/sms.cfm"}
		handle = self.request(url, headers, params)
		if handle.geturl() == "https://www.mymeteor.ie/mymeteor/system/view/smssent.cfm":
			return True
		return False
	
	def getPhoneBook(self):
		params = urllib.urlencode({
			'msisdn': "",
			'sms_text': "",
			'formName' : "smsForm",
			'mum_left' : "160",
			'phonebook' : "Please wait...",
			'sendSMS' : "Please wait...",
			'clicked' : "1",
			'action' : "Select From Phonebook",
			'method': "SMS",
			'returnTo': "/mymeteor/system/view/sms.cfm",
			'business_r29_c52': "true"
		})
		url = 'https://www.mymeteor.ie/mymeteor/system/controllers/controller.cfc'
		headers ={'User-agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)',
				  'Cookie' : self.cookie,
				  'Referer' : "https://www.mymeteor.ie/mymeteor/system/view/sms.cfm"}
		handle = self.request(url, headers, params)
		if handle.geturl() == "https://www.mymeteor.ie/mymeteor/system/view/smsphonebook.cfm":
			htmlPhoneBook = handle.read().split("\n")
			phonebook = {}
			for line in htmlPhoneBook:
				if line[34:44] == "contactIds":
					entry = line[53:-7].split("~")
					phonebook[entry[1]] = (entry[0], entry[2])
			#for key in phonebook:
			#	print key, ":", phonebook[key][1]
		return phonebook
		
	def request(self, url, headers, params=None):
		try:
			req = urllib2.Request(url, params, headers)
			handle = urllib2.urlopen(req)
		except IOError, e:
			print 'We failed to open "%s".' % theurl
			if hasattr(e, 'code'):
				print 'We failed with error code - %s.' % e.code
			elif hasattr(e, 'reason'):
				print "The error object has the following 'reason' attribute :", e.reason
				print "This usually means the server doesn't exist, is down, or we don't have an internet connection."
		return handle
		#print handle.info() # handle.read() returns the page, handle.geturl() returns the true url of the page fetched (in case urlopen has followed any redirects, which it sometimes does)
